<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">{{ $t('login.form.title') }}</div>
    <!--副标题就不要了-->
    <!--<div class="login-form-sub-title">{{ $t('login.form.title') }}</div>-->
    <!--  这里是处理报错的 比如用户名、手机号重复的问题   -->
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" title="用户名" style="margin-top: 20px">
        <a-form
          ref="loginForm"
          :model="userInfo"
          class="login-form"
          layout="vertical"
          @submit="handleSubmit"
        >
          <!--message 是在错误的时候显示
        validate-trigger  校验
      -->
          <a-form-item
            field="username"
            :rules="[
              { required: true, message: $t('login.form.userName.errMsg') },
            ]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input
              v-model="userInfo.username"
              :placeholder="$t('login.form.userName.placeholder')"
            >
              <template #prefix>
                <icon-user />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item
            field="password"
            :rules="[
              { required: true, message: $t('login.form.password.errMsg') },
            ]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input-password
              v-model="userInfo.password"
              :placeholder="$t('login.form.password.placeholder')"
              allow-clear
            >
              <template #prefix>
                <icon-lock />
              </template>
            </a-input-password>
          </a-form-item>
          <a-space :size="16" direction="vertical">
            <div class="login-form-password-actions">
              <a-checkbox
                checked="rememberPassword"
                :model-value="loginConfig.rememberPassword"
                @change="(setRememberPassword as any)"
              >
                {{ $t('login.form.rememberPassword') }}
              </a-checkbox>
              <!--这里是忘记密码-->
              <a-link>{{ $t('login.form.forgetPassword') }}</a-link>
            </div>
            <a-button type="primary" html-type="submit" long :loading="loading">
              {{ $t('login.form.login') }}
            </a-button>
            <!--<<<<<<< HEAD-->
            <!--        <a-button-->
            <!--          type="text"-->
            <!--          long-->
            <!--          class="login-form-register-btn"-->
            <!--          @click="handleClick"-->
            <!--=======-->
            <!--        &lt;!&ndash; <a-button-->
            <!--          type="text"-->
            <!--          long-->
            <!--          class="login-form-register-btn"-->
            <!--          @click="switchSignUp"-->
            <!--&gt;>>>>>> 29d0874697cf4345c774f657e1cd45d3d59aa780-->
            <!--        >-->
            <!--          {{ $t('login.form.register') }}-->
            <!--        </a-button> &ndash;&gt;-->
          </a-space>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" title="手机号" style="margin-top: 20px">
        <a-form
          ref="loginForm"
          :model="phoneForm"
          class="login-form"
          layout="vertical"
          @submit="phoneSubmit"
        >
          <a-form-item
            field="phone"
            :rules="[
              { required: true, message: $t('login.form.phone.errMsg') },
            ]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input
              v-model="phoneForm.phone"
              :placeholder="$t('login.form.phone.placeholder')"
            >
              <template #prefix>
                <icon-phone />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item
            field="verificationCode"
            :rules="[
              {
                required: true,
                message: $t('login.form.verificationCode.errMsg'),
              },
            ]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input
              v-model="phoneForm.verificationCode"
              :placeholder="$t('login.form.verificationCode.placeholder')"
              allow-clear
            >
              <template #prefix>
                <icon-cloud />
              </template>
            </a-input>
            <div>
              <a-button type="primary" @click="sendVcode">发送验证码</a-button>
            </div>
          </a-form-item>
          <a-space :size="16" direction="vertical">
            <a-button type="primary" html-type="submit" long :loading="loading">
              {{ $t('login.form.login') }}
            </a-button>
          </a-space>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </div>
  <div>
    <!--注册部分-->
    <!--弹出的一个表单-->
    <!-- <a-modal
      v-model:visible="visibleRegister"
      title="用户注册"
      @cancel="handleCancel"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="form">
        <a-form-item field="name" label="用户名">
          <a-input v-model="form.register_username" />
        </a-form-item>
        <a-form-item field="phone" label="手机号">
          <a-input v-model="form.register_phone" />
        </a-form-item>
        <a-form-item field="password" label="密码">
          <a-input v-model="form.register_password" />
        </a-form-item>
        <a-form-item field="password_confirm" label="密码确认">
          <a-input v-model="form.register_password_confirm" />
        </a-form-item>
      </a-form>
    </a-modal> -->
  </div>

  <!--&lt;!&ndash;找回密码部分&ndash;&gt;-->
  <!--<div>-->
  <!--  &lt;!&ndash;注册部分&ndash;&gt;-->
  <!--  &lt;!&ndash;弹出的一个表单&ndash;&gt;-->
  <!--  <a-modal v-model:visible="visibleRegister" title="用户注册" @cancel="handleCancel" @before-ok="handleBeforeOk">-->
  <!--    <a-form :model="form">-->
  <!--      <a-form-item field="name" label="用户名"-->
  <!--      >-->
  <!--        <a-input v-model="form.register_username" />-->
  <!--      </a-form-item>-->
  <!--      <a-form-item field="phone" label="手机号">-->
  <!--        <a-input v-model="form.register_phone" />-->
  <!--      </a-form-item>-->
  <!--      <a-form-item field="password" label="密码">-->
  <!--        <a-input v-model="form.register_password" />-->
  <!--      </a-form-item>-->
  <!--      <a-form-item field="password_confirm" label="密码确认">-->
  <!--        <a-input v-model="form.register_password_confirm" />-->
  <!--      </a-form-item>-->
  <!--    </a-form>-->
  <!--  </a-modal>-->
  <!--</div>-->
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import { sendCode } from '@/api/user';
  import type { LoginData } from '@/api/user';
  import { successResponseWrap } from '@/utils/setup-mock';

  const router = useRouter();
  const { t } = useI18n();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();

  const visibleRegister = ref(false);
  const form = reactive({
    register_username: '',
    register_password: '',
    register_phone: '',
    register_password_confirm: '',
  });
  // 手机号表单
  const phoneForm = reactive({
    phone: '',
    verificationCode: '',
  });

  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    username: 'admin', // 演示默认值
    password: 'admin', // demo default value
  });
  const userInfo = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
  });
  // 二维码 的 变量 --王启月
  const vcode = ref();
  function switchSignUp() {
    router.push('signUp');
  }

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        const id = await userStore.login(values as LoginData);
        console.log('登录');
        console.log(id);
        console.log('登录');

        userStore.$state.id = id;
        console.log(`登录后有记录吗
        ${userStore.$state.id}`);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        console.log(redirect);
        // console.log(othersQuery)

        // 这里就是发送请求
        // 是vue的路由 不能算是请求，因为是router
        router.push({
          name: (redirect as string) || 'UserSearchTable',
          query: {
            ...othersQuery,
          },
        });

        Message.success(t('login.form.login.success'));
        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        console.log('----------');
        console.log(rememberPassword);
        console.log(loginConfig.value);
        console.log(values);
        // 实际生产环境需要进行加密存储。
        // The actual production environment requires encrypted storage.
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';

        // 这里应该是给权限
        // if (username === 'admin' && password === 'admin') {
        //   window.localStorage.setItem('userRole', 'admin');
        //   // eslint-disable-next-line consistent-return
        //   return successResponseWrap({
        //     token: '12345',
        //   });
        // }
        // if (username === 'user' && password === 'user') {
        //   window.localStorage.setItem('userRole', 'user');
        //   // eslint-disable-next-line consistent-return
        //   return successResponseWrap({
        //     token: '54321',
        //   });
        // }
        // if (username === 'tenant' && password === 'tenant') {
        //   window.localStorage.setItem('userRole', 'tenant');
        //   // eslint-disable-next-line consistent-return
        //   return successResponseWrap({
        //     token: '54321',
        //   });
        // }
        // if (username === 'respondent' && password === 'respondent') {
        //   window.localStorage.setItem('userRole', 'respondent');
        //   // eslint-disable-next-line consistent-return
        //   return successResponseWrap({
        //     token: '54321',
        //   });
        // }

        console.log(loginConfig.value);
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };

  // 发送验证码
  const sendVcode = async () => {
    Message.success('已发送');
    const res = await sendCode(phoneForm.phone);
    vcode.value = res.data;
  };
  const phoneSubmit = async ({ errors, values }: { errors; values }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        if (vcode.value !== values.verificationCode) {
          console.log(vcode.value);
          console.log(values.verificationCode);

          Message.error('输入验证码有误');
        } else {
          await userStore.phoneLogin(values);
          console.log(router.currentRoute.value.query);
          const { redirect, ...othersQuery } = router.currentRoute.value.query;
          console.log(redirect);
          // console.log(othersQuery)
          // 这里就是发送请求
          // 是vue的路由 不能算是请求，因为是router
          router.push({
            name: (redirect as string) || 'Workplace',
            query: {
              ...othersQuery,
            },
          });

          Message.success(t('login.form.login.success'));
          const { rememberPassword } = loginConfig.value;
          const { username, password } = values;
          console.log('----------');
          console.log(rememberPassword);
          console.log(loginConfig.value);
          console.log(values);
          // 实际生产环境需要进行加密存储。
          // The actual production environment requires encrypted storage.
          loginConfig.value.username = rememberPassword ? username : '';
          loginConfig.value.password = rememberPassword ? password : '';
          console.log(loginConfig.value);
        }
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };

  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };

  // 注册的
  const handleClick = () => {
    visibleRegister.value = true;
  };
  const handleBeforeOk = (done) => {
    console.log(form);
    if (form.register_password !== form.register_password_confirm) {
      Message.error('两次密码不一致');
    }
    window.setTimeout(() => {
      done();
      // prevent close
      // done(false)
    }, 3000);
  };
  const handleCancel = () => {
    visibleRegister.value = false;
  };
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 320px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
